package com.yuyou.fn.crm.service.impl;

import com.github.wens.framework.service.impl.SuperServiceImpl;
import com.github.wens.mybatisplus.examples.Example;
import com.github.wens.mybatisplus.plugins.Page;
import com.yuyou.fn.common.util.BeanUtils;
import com.yuyou.fn.common.util.CriteriaUtils;
import com.yuyou.fn.common.util.Utils;
import com.yuyou.fn.crm.entity.CrmCommunicateHistory;
import com.yuyou.fn.crm.entity.CrmStudentCommunicate;
import com.yuyou.fn.crm.mapper.CrmStudentCommunicateMapper;
import com.yuyou.fn.crm.service.ICrmCommunicateHistoryService;
import com.yuyou.fn.crm.service.ICrmStudentCommunicateService;
import com.yuyou.fn.crm.vo.CommunicateSituationQueryVo;
import com.yuyou.fn.crm.vo.CommunicateSituationVo;
import com.yuyou.fn.crm.vo.CrmStudentCommunicateQueryVo;
import com.yuyou.fn.educational.entity.BaseGrade;
import com.yuyou.fn.educational.service.IBaseGradeService;
import com.yuyou.fn.educational.service.IStudentRegService;
import com.yuyou.fn.report.entity.MergeStudentRegDetail;
import com.yuyou.fn.report.service.IMergeStudentRegDetailService;
import com.yuyou.fn.report.vo.StudentRegDetailQueryVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * CrmStudentCommunicate 表数据服务层接口实现类
 */
@Service
public class CrmStudentCommunicateServiceImpl extends SuperServiceImpl<CrmStudentCommunicateMapper, CrmStudentCommunicate, Long> implements ICrmStudentCommunicateService {

    @Resource
    private IStudentRegService studentRegService;

    @Resource
    private ICrmCommunicateHistoryService crmCommunicateHistoryService;

    @Resource
    private IMergeStudentRegDetailService mergeStudentRegDetailService;

    @Resource
    private IBaseGradeService baseGradeService;

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public Page<CrmStudentCommunicate> findCommunicatePageByQueryVo(CrmStudentCommunicateQueryVo crmStudentCommunicateQueryVo, int pageNo, int pageSize) {
        Example<CrmStudentCommunicate> crmStudentCommunicateExample = CrmStudentCommunicate.createExample();
        Example.Criteria criteria = crmStudentCommunicateExample.createCriteria();
        CriteriaUtils.fillCondition(criteria, crmStudentCommunicateQueryVo);
        criteria.andGreaterThan("regNum", 0);
        return findPageByExample(crmStudentCommunicateExample, pageNo, pageSize);
    }

    @Override
    public SXSSFWorkbook exportStudentCommunicate(CrmStudentCommunicateQueryVo crmStudentCommunicateQueryVo) {
        Page<CrmStudentCommunicate> crmStudentCommunicatePage = this.findCommunicatePageByQueryVo(crmStudentCommunicateQueryVo, 1, 20000);
        List<CrmStudentCommunicate> crmStudentCommunicateList = crmStudentCommunicatePage.getRecords();
        List<Long> studentCommunicateIdList = BeanUtils.toList(crmStudentCommunicateList, "studentCommunicateId");
        List<CrmCommunicateHistory> crmCommunicateHistoryList = crmCommunicateHistoryService.findCommunicateHistoryByCommunicateIds(studentCommunicateIdList);
        List<BaseGrade> baseGradeList = baseGradeService.findAllFromCache();
        Map<Long, BaseGrade> map = BeanUtils.toMap(baseGradeList, "gradeId");
        return studentCommunicate2excel(crmStudentCommunicateList, crmCommunicateHistoryList, map);
    }

    public static SXSSFWorkbook studentCommunicate2excel(List<CrmStudentCommunicate> crmStudentCommunicateList, List<CrmCommunicateHistory> crmCommunicateHistoryList, Map<Long, BaseGrade> map) {

        SXSSFWorkbook excel = new SXSSFWorkbook();
        SXSSFSheet sheet = excel.createSheet("家校沟通");
        SXSSFRow firstRow = sheet.createRow(0);
        String[] titles = new String[]{"学生姓名", "学生电话", "学号", "报读期数", "生源类型", "报读年级", "段次", "报读业务组", "班主任", "沟通时间", "沟通内容"};
        for (int i = 0; i < titles.length; i++) {
            firstRow.createCell(i).setCellValue(titles[i]);
        }
        int rowNum = 1;

        Map<Long, CrmStudentCommunicate> studentCommunicateMap = BeanUtils.toMap(crmStudentCommunicateList, "studentCommunicateId");

        if (crmCommunicateHistoryList != null) {
            for (CrmCommunicateHistory crmCommunicateHistory : crmCommunicateHistoryList) {
                CrmStudentCommunicate crmStudentCommunicate = studentCommunicateMap.get(crmCommunicateHistory.getStudentCommunicateId());
                int cellNum = 0;

                SXSSFRow row = sheet.createRow(rowNum++);

                SXSSFCell cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(crmStudentCommunicate.getStudentName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(crmStudentCommunicate.getStudentPhoneNo()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(crmStudentCommunicate.getStudentNo()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(crmStudentCommunicate.getPeriodName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(crmStudentCommunicate.getStudentState() == null ? "" : crmStudentCommunicate.getStudentState() == 0 ? "新生" : crmStudentCommunicate.getStudentState() == 1 ? "老生" : "续读生");


                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(map.get(crmStudentCommunicate.getGradeId()) == null ? "" : map.get(crmStudentCommunicate.getGradeId()).getGradeName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(crmStudentCommunicate.getSegmentNo() == null ? "" : crmStudentCommunicate.getSegmentNo().toString());


                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(crmStudentCommunicate.getBusTeamName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(crmStudentCommunicate.getSeniorName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(crmCommunicateHistory.getCommunicateDate() == null ? "" : Utils.formatDate(crmCommunicateHistory.getCommunicateDate(), "yyyy-MM-dd"));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(crmCommunicateHistory.getCommunicateContent()));

            }
        }

        return excel;
    }

    @Override
    public List<CrmStudentCommunicate> findCommunicateListByQueryVo(CrmStudentCommunicateQueryVo crmStudentCommunicateQueryVo) {
        Example<CrmStudentCommunicate> crmStudentCommunicateExample = CrmStudentCommunicate.createExample();
        Example.Criteria criteria = crmStudentCommunicateExample.createCriteria();
        CriteriaUtils.fillCondition(criteria, crmStudentCommunicateQueryVo);
        criteria.andGreaterThan("regNum", 0);
        return findListByExample(crmStudentCommunicateExample);
    }

    @Override
    public CrmStudentCommunicate findByQueryVo(CrmStudentCommunicateQueryVo crmStudentCommunicateQueryVo) {
        Example<CrmStudentCommunicate> crmStudentCommunicateExample = CrmStudentCommunicate.createExample();
        Example.Criteria criteria = crmStudentCommunicateExample.createCriteria();
        CriteriaUtils.fillCondition(criteria, crmStudentCommunicateQueryVo);
        return findOneByExample(crmStudentCommunicateExample);
    }

    @Override
    public Long countCommunicateByQueryVo(CrmStudentCommunicateQueryVo crmStudentCommunicateQueryVo) {
        Example<CrmStudentCommunicate> crmStudentCommunicateExample = CrmStudentCommunicate.createExample();
        Example.Criteria criteria = crmStudentCommunicateExample.createCriteria();
        CriteriaUtils.fillCondition(criteria, crmStudentCommunicateQueryVo);
        return countByExample(crmStudentCommunicateExample);
    }

    @Override
    public List<MergeStudentRegDetail> findStudentRegByCommunicateId(Long studentCommunicateId) {
        CrmStudentCommunicate crmStudentCommunicate = this.findById(studentCommunicateId);
        StudentRegDetailQueryVo studentRegDetailQueryVo = new StudentRegDetailQueryVo();
        studentRegDetailQueryVo.setStudentId(crmStudentCommunicate.getStudentId());
        studentRegDetailQueryVo.setAreaTeamId(crmStudentCommunicate.getAreaTeamId());
        studentRegDetailQueryVo.setBusTeamId(crmStudentCommunicate.getBusTeamId());
        studentRegDetailQueryVo.setSeniorId(crmStudentCommunicate.getSeniorId());
        studentRegDetailQueryVo.setPeriodId(crmStudentCommunicate.getPeriodId());
        studentRegDetailQueryVo.setSegmentNo(crmStudentCommunicate.getSegmentNo());
        studentRegDetailQueryVo.setGradeId(crmStudentCommunicate.getGradeId());
        studentRegDetailQueryVo.setStudentState(crmStudentCommunicate.getStudentState());
        studentRegDetailQueryVo.setRegStatus(0);
        Page<MergeStudentRegDetail> page = mergeStudentRegDetailService.findStudentRegByQuery(studentRegDetailQueryVo, 1, 20000);
        return page.getRecords();
    }

    @Override
    public Page<CommunicateSituationVo> findCommunicateSituation(CommunicateSituationQueryVo communicateSituationQueryVo, int pageNo, int pageSize) {
        List<CommunicateSituationVo> communicateSituationVoList = autoMapper.findCommunicateSituation(communicateSituationQueryVo, (pageNo - 1) * pageSize, pageSize);
        Integer total = autoMapper.countCommunicateSituation(communicateSituationQueryVo);
        Page<CommunicateSituationVo> communicateSituationVoPage = new Page<>(pageNo, pageSize);
        communicateSituationVoPage.setRecords(communicateSituationVoList);
        communicateSituationVoPage.setTotal(total);
        return communicateSituationVoPage;
    }

    @Override
    public SXSSFWorkbook exportCommunicateSituation(CommunicateSituationQueryVo communicateSituationQueryVo) {
        List<CommunicateSituationVo> communicateSituationVoList = autoMapper.findCommunicateSituation(communicateSituationQueryVo, 0, 50000);

        return communicateSituation2excel(communicateSituationVoList);
    }

    public static SXSSFWorkbook communicateSituation2excel(List<CommunicateSituationVo> communicateSituationVoList) {

        SXSSFWorkbook excel = new SXSSFWorkbook();
        SXSSFSheet sheet = excel.createSheet("沟通情况");
        SXSSFRow firstRow = sheet.createRow(0);
        String[] titles = new String[]{"业务组", "班主任", "期数", "所带学生人数", "已沟通人数（沟通次数=1）", "已沟通人数（沟通次数>=2）", "未沟通人数", "沟通率"};
        for (int i = 0; i < titles.length; i++) {
            firstRow.createCell(i).setCellValue(titles[i]);
        }
        int rowNum = 1;

        if (communicateSituationVoList != null) {
            for (CommunicateSituationVo communicateSituationVo : communicateSituationVoList) {
                int cellNum = 0;

                SXSSFRow row = sheet.createRow(rowNum++);

                SXSSFCell cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(communicateSituationVo.getSeniorBusTeamName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(communicateSituationVo.getSeniorName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(communicateSituationVo.getPeriodName()));

                cell = row.createCell(cellNum++);
                cell.setCellType(CellType.NUMERIC);
                cell.setCellValue(communicateSituationVo.getTotalStudentNum());

                cell = row.createCell(cellNum++);
                cell.setCellType(CellType.NUMERIC);
                cell.setCellValue(communicateSituationVo.getBigOne());

                cell = row.createCell(cellNum++);
                cell.setCellType(CellType.NUMERIC);
                cell.setCellValue(communicateSituationVo.getBigTwo());

                cell = row.createCell(cellNum++);
                cell.setCellType(CellType.NUMERIC);
                cell.setCellValue(communicateSituationVo.getUnCommunicateNum());

                cell = row.createCell(cellNum++);
                cell.setCellValue(Utils.doubleToPercent(communicateSituationVo.getCommunicateRate()));


            }
        }


        return excel;
    }

    @Override
    public void updateCrmStudentCommunicateBatch(List<CrmStudentCommunicate> crmStudentCommunicates) {
        autoMapper.updateCrmStudentCommunicateBatch(crmStudentCommunicates);
    }
}